﻿using System.Collections.Generic;
using System.Data;
using DataScripter.Containers;
using DataScripter.Scripting.InputSources;
using DataScripter.Scripting.Processes.Output;
using DataScripter.Scripting.ScriptDefinitions;
using DataScripter.Sorters;

namespace DataScripter.Scripting.Processes
{
    class ReadToDataSetProcess : BaseProcess
    {
        private IInputSource InputSource { get; set; }
        private IScriptDefinition ScriptDefinition { get; set; }
        private ISorter<ITableScriptRequest> TableStructureSorter { get; set; }

        public ReadToDataSetProcess(string name, IContainer container) : base(name, container)
        {
        }

        public override void Initialize(Dictionary<string, string> parameters)
        {
            InputSource = GetTypedParameter<IInputSource>(parameters, "InputSource");
            ScriptDefinition = GetTypedParameter<IScriptDefinition>(parameters, "ScriptDefinition");
            TableStructureSorter = GetTypedParameter<ISorter<ITableScriptRequest>>(parameters, "Sorter");
        }

        public override IProcessOutput Run()
        {
            RunParents();

            if (State == ProcessState.Error)
                return null;

            InputSource.Initialize();
            IDataProducer dataProducer = InputSource.Resolve<IDataProducer>();

            DataSet dataSet = new DataSet();
            foreach (ITableScriptRequest tableScriptRequest in TableStructureSorter.Sort(ScriptDefinition.ScriptRequests.Values))
            {
                using (IDataReader reader = dataProducer.ProduceData(tableScriptRequest))
                {
                    dataSet.Load(reader, LoadOption.Upsert, tableScriptRequest.TableName);
                }
            }
            Output = new DataSetProcessOutput(dataSet);
            State = ProcessState.Ended;
            return Output;
        }
    }
}
